package com.change.zh.ffmpegdo.push;

import java.util.Collection;
import java.util.Iterator;

public class FFmpegManager {

    private JobSingleDB jobDB = JobSingleDB.Instance();
    private JobCommandExec jobCommandExec = new JobCommandExec();

    public String start(String id, String type, String command) {
        if (id != null && command != null) {
            JobDetail jobDetail = jobCommandExec.process(id, type, command);
            if (jobDetail != null) {
                int ret = jobDB.add(jobDetail);
                if (ret > 0) {
                    return jobDetail.toString();
                } else {
                    // 持久化信息失败，停止处理
                    jobCommandExec.stop((CommandConsoleThread) jobDetail.getThread());
                    jobCommandExec.stop(jobDetail.getProcess());
                }
            }
        }
        return null;
    }


    public boolean stop(String id) {
        if (id != null && jobDB.isHave(id)) {
            System.out.println("正在停止任务：" + id);
            JobDetail jobDetail = jobDB.get(id);
            if (jobCommandExec.stop((CommandConsoleThread) jobDetail.getThread()) && jobCommandExec.stop(jobDetail.getProcess())) {
                jobDB.remove(id);
                return true;
            }
        }
        System.err.println("停止任务失败！id=" + id);
        return false;
    }

    public int stopAll() {
        Collection<JobDetail> list = jobDB.getAll();
        Iterator<JobDetail> iter = list.iterator();
        JobDetail jobDetail = null;
        int index = 0;
        while (iter.hasNext()) {
            jobDetail = iter.next();
            if (jobCommandExec.stop((CommandConsoleThread) jobDetail.getThread()) && jobCommandExec.stop(jobDetail.getProcess())) {
                jobDB.remove(jobDetail.getId());
                index++;
            }
        }
        System.out.println("停止了" + index + "个任务！");
        return index;
    }

    public JobDetail query(String id) {
        return jobDB.get(id);
    }

    public Collection<JobDetail> queryAll() {
        return jobDB.getAll();
    }
}
